import { login, getUserInfo } from '@/api/user'
import {TokenKey} from '@/config/index.js'
export default {
	namespaced: true,
	state: {
		token: uni.getStorageSync("token") || "",
		userInfo: {}, // 用户信息
	},
	getters: {
		token: state => state.token,
		isLogin: state => !!state.userInfo.id,
		userInfo: state => state.userInfo
	},
	mutations: {
		token(state, payload) {
			state.token = payload;
			uni.setStorageSync("token", payload);
		},
		
		// 用户信息
		userInfo(state, data) {
			state.userInfo = data;
		},
	},
	actions: {
		getUserInfo({ commit,state },refresh=true) {
			if(!refresh&&state.userInfo.id){
				return Promise.resolve(state.userInfo)
			}
			
			
			return new Promise((reslove, reject) => {
				getUserInfo().then(res => {
					commit('userInfo', res.data);
					reslove(res.data)
				}).catch(err => {
					reject(err);
				})
			})
		},
		logout({ commit }) {
			return new Promise((reslove, reject) => {
				uni.removeStorage({
					key: TokenKey,
					success() {
						commit('userInfo', '');
						// uni.navigateTo({ url: '/pages/login/login' })
						reslove()
					},
					fail() {
						reject()
					},
					complete: () => {
						uni.navigateTo({ url: '/pages/login/login' })
					}
				})

			})
		}
	}
}
